package evi.com.evi.fragment;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

import cn.jpush.android.api.JPushInterface;
import evi.com.evi.R;
import evi.com.evi.application.MyApplication;
import evi.com.evi.login.LoginActivity;
import evi.com.evi.login.LoginByCodeActivity;
import evi.com.evi.utils.AppUtils;
import evi.com.evi.utils.ChannelStatusConsts;
import evi.com.evi.utils.ConnectUtil;
import evi.com.evi.utils.ContentUtils;
import evi.com.evi.utils.HeartBreakUtil;
import evi.com.evi.utils.JSONUtils;
import evi.com.evi.utils.SPUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SettingFragment extends Fragment implements OnClickListener {
    private View view;

    private RelativeLayout rl_01;
    private RelativeLayout rl_02;
    private RelativeLayout rl_03;
    private TextView tv_logout;

    private TextView tv011;

    private ImageView iv_next2;
    private boolean isSwitch;

    private OkHttpClient client;
    private JSONUtils jsonUtils;

    private String token;

    private Dialog dialog;

    /*** 声音震动变量 **/
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private Dialog soundDialog;
    // 作为配置铃声标识 1 第一个 2第二个 3第三个 此处可作为一个app的全局变量保存
    private static int SOUNDTYE = -1;
    MediaPlayer mPlayer;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_setting, container, false);
        initView();
        return view;
    }

    private void initView() {
        rl_01 = (RelativeLayout) view.findViewById(R.id.rl_01);
        rl_02 = (RelativeLayout) view.findViewById(R.id.rl_02);
        rl_03 = (RelativeLayout) view.findViewById(R.id.rl_03);
        tv_logout = (TextView) view.findViewById(R.id.tv_logout);
        tv011 = (TextView) view.findViewById(R.id.tv011);

        String soundType = SPUtil.getString(getActivity(), "soundType");
        if ("0".equals(soundType)) {
            tv011.setText("第一个铃音");
        } else if ("1".equals(soundType)) {
            tv011.setText("第二个铃音");
        } else if ("2".equals(soundType)) {
            tv011.setText("第三个铃音");
        } else {
            tv011.setText("第一个铃音");
        }

        rl_01.setOnClickListener(this);
        rl_02.setOnClickListener(this);
        rl_03.setOnClickListener(this);
        tv_logout.setOnClickListener(this);
        client = new OkHttpClient();
        jsonUtils = new JSONUtils();

        iv_next2 = (ImageView) view.findViewById(R.id.iv_next2);
        iv_next2.setOnClickListener(this);

        isSwitch = SPUtil.getBoolean(getActivity(),"isSwitch");

        token = SPUtil.getString(MyApplication.getInstance().getApplicationContext(), "token");
        if (isSwitch) {
            iv_next2.setImageResource(R.drawable.ic_switch_on);
        } else {
            iv_next2.setImageResource(R.drawable.ic_switch_off);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_01:        //铃声设置
                SelectSoundDialog();
                break;
            case R.id.iv_next2:        //开关
                if (isSwitch) {
                    isSwitch = false;
                    SPUtil.setBoolean(getActivity(),"isSwitch",isSwitch);
                    iv_next2.setImageResource(R.drawable.ic_switch_off);
                } else {
                    isSwitch = true;
                    SPUtil.setBoolean(getActivity(),"isSwitch",isSwitch);
                    iv_next2.setImageResource(R.drawable.ic_switch_on);
                }
                break;
            case R.id.rl_02:        //提示震动

                break;

            case R.id.rl_03:        //联系客服
                phone("4009003736");
                break;

            case R.id.tv_logout:        //退出登录
                exit();
                break;
            default:
                break;
        }
    }

    //拨打电话
    public void phone(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    //退出登陆
    private void exit() {
        dialog = AppUtils.getLoadingDialog(getActivity(), "提示", "正在退出");
        dialog.show();
        new HeartBreakUtil().stopRepeatTask("YW_EVI_HEART_BREAK_EVENT");
        HeartBreakUtil.sendHeartBreakPacket(client, getActivity(), ChannelStatusConsts.CHANNEL_STATUS_REST);

        Request request = new Request.Builder()
                .url(ContentUtils.quit_url)
                .addHeader("token",token)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                toast("网络信号不佳，加载失败");
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ConnectUtil.isConnect(getActivity())){
                            toast("网络信号不佳，加载失败");
                        } else {
                            toast("网络未联接，请检查");
                        }
                    }
                });
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                startActivity(intent);
                                getActivity().finish();
                                JPushInterface.stopPush(MyApplication.getContext());
                                SPUtil.exit(getActivity());
                                Log.d("TAG", "退出登录，停止极光推送");
                            }
                        });
                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
            }
        });
    }

    /***
     * 选择不同铃声 @ 用于不同地方调用 可自行封装在util里
     *
     * @param id
     */
    private void SelectSoundPlay(int id) {
        if (mPlayer != null) {
            mPlayer = null;
        }
        mPlayer = MediaPlayer.create(getActivity(), id);
        mPlayer.start();
//        mPlayer.release();
    }

    //播放声音的dialog
    public void SelectSoundDialog() {
        if (null != soundDialog && soundDialog.isShowing()) {
            return;
        }
        soundDialog = new Dialog(getActivity(), R.style.loading_dialog);
        View view = View.inflate(getActivity(),
                R.layout.zzzz_sound_dialog, null);
        TextView tv_sound1 = (TextView) view.findViewById(R.id.tv_sound1);
        TextView tv_sound2 = (TextView) view.findViewById(R.id.tv_sound2);
        TextView tv_sound3 = (TextView) view.findViewById(R.id.tv_sound3);
        tv_sound1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SelectSoundPlay(R.raw.hongbao_gq);
                SOUNDTYE = 0;// 选择第一种铃声
                SPUtil.setString(getActivity(), "soundType", SOUNDTYE + "");
                tv011.setText("第一个铃音");
                soundDialog.dismiss();
            }
        });
        tv_sound2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SelectSoundPlay(R.raw.hongbao_gx);
                SOUNDTYE = 1;// 选择第二种铃声
                SPUtil.setString(getActivity(), "soundType", SOUNDTYE + "");
                tv011.setText("第二个铃音");
                soundDialog.dismiss();
            }
        });
        tv_sound3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SelectSoundPlay(R.raw.phonering);
                SOUNDTYE = 2;// 选择第三种铃声
                SPUtil.setString(getActivity(), "soundType", SOUNDTYE + "");
                tv011.setText("第三个铃音");
                soundDialog.dismiss();
            }
        });
        soundDialog.setContentView(view);
        soundDialog.setCanceledOnTouchOutside(true);
        soundDialog.show();
    }

    private void toast(final String string) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getActivity(), string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void dismiss() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // TODO Auto-generated method stub
        if (mPlayer != null){
            if (mPlayer.isPlaying()) {
                mPlayer.stop();
            }
            mPlayer.release();// 释放资源
        }
    }
}
